<canvas width="480" height="320" id="draw"></canvas>
<button onClick="sketch.clean()">Clear Canvas</button>

<p>Draw your sketch in this box. Extract the pen strokes by running `sketch.data()` in the console.</p>

<style>
  #draw {
    border: 1px dashed black;
    cursor: crosshair;
  }
</style>

<script>

function makeDrawable(canvas) {
  const ctx = canvas.getContext('2d');
  const fillColor = "#000";

  ctx.fillStyle = fillColor;
  ctx.lineWidth = 10;
  ctx.lineCap = "round";
  ctx.imageSmoothingEnabled = true;

  let isDrawing = false;
  let prevPos = null;
  
  const penStrokes = [];

  function draw(event) {
    if (isDrawing) {
      drawLineTo(getCursorPos(event));
    }
  }

  function getCursorPos(event) {
    return [event.offsetX, event.offsetY];
  }

  function drawLineTo(pos) {
    if (prevPos) {
      ctx.beginPath();
      ctx.moveTo(prevPos[0], prevPos[1]);
      ctx.lineTo(pos[0], pos[1]);
      ctx.stroke();

      // collect pen strokes
      penStrokes.push({
        dx: pos[0] - prevPos[0],
        dy: pos[1] - prevPos[1],
        touch: true,
        lift: false,
      });
    }
    prevPos = pos;
  }

  const size = 10;
  function drawPixel(pos) {
    ctx.fillRect(pos[0], pos[1], size, size);
  }

  function fillCanvas(color) {
    ctx.fillStyle = color;
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    ctx.fillStyle = fillColor;
  }

  canvas.onmousedown = () => {
    isDrawing = true;
  }
  canvas.onmouseup = () => {
    isDrawing = false;
    prevPos = null; 
    penStrokes[penStrokes.length - 1].touch = false;
    penStrokes[penStrokes.length - 1].lift = true;
  }

  return {
    start: () => canvas.onmousemove = draw,
    stop: () => canvas.onmousemove = null,
    clean: () => {
      fillCanvas("#FFF");
      penStrokes = [];
    },
    data: () => penStrokes
  }
}

const sketch = makeDrawable(document.getElementById('draw'));
sketch.start();

</script>
</body>